import { defineStore } from "pinia";
import { ref } from "vue";
import { getVacationBalance, updateVacationBalance } from "@/api/vacation";
import type {
  EmployeeBalance,
  UpdateBalanceParams,
} from "@/api/types/vacation";

import { ElMessage } from "element-plus";

interface LeaveMap {
  [key: string]: string | number;
}

export const useVacationBalanceStore = defineStore("vacationBalance", () => {
  const balanceList = ref<EmployeeBalance[]>([]);
  const loading = ref(false);

  // 获取假期余额列表
  const fetchBalanceList = async (val:any) => {    
    loading.value = true;
    try {
      const res = await getVacationBalance(val);
      if (res.code === "200") {
        balanceList.value = res.data.map((item) => {          
          // 构造基础数据
          const employee = {
            count:res.count,
            userid: item.userid,
            username: item.username,
            department: item.dept_name,
            joinDate: item.timeOfEntry,
            firstWorkDate: "-",
            holidaylist:item.holidaylist
          };

          const leaves = {};
          if (item.holidaylist?.length > 0)
            item.holidaylist?.forEach(
              (v) => (leaves[`${v.leaveName}${v.leave_code}`] = v.quota_num)
            );

            

          // 返回合并后的数据
          return {
            ...employee,
            ...leaves,
          };
        });
        
      } else {
        ElMessage.error(res.msg || "获取假期余额失败");
      }
    } catch (error) {
      console.error("获取假期余额失败:", error);
      ElMessage.error("获取假期余额失败");
    } finally {
      loading.value = false;
    }
  };

  // 更新假期余额
  const updateBalance = async (params: UpdateBalanceParams) => {
    try {
      const res = await updateVacationBalance(params);
      if (res.code === "200") {
        ElMessage.success(res.msg || "修改成功");
        // await fetchBalanceList(); // 重新获取列表
        return true;
      } else {
        ElMessage.error(res.msg || "修改失败");
        return false;
      }
    } catch (error) {
      console.error("更新假期余额失败:", error);
      ElMessage.error("更新失败");
      return false;
    }
  };

  return {
    balanceList,
    loading,
    fetchBalanceList,
    updateBalance,
  };
});
